#include <iostream>
#include <unistd.h>
#include <pthread.h>
#include <time.h>

const int N = 4;

pthread_mutex_t mutex;
int ticket = 10000;

void* GetTicket(void* args)
{
    const char* name = static_cast<char*>(args);
    while (true)
    {
        pthread_mutex_lock(&mutex);
        if (ticket > 0)
        {
            usleep(1000);
            printf("%s[%ld]get a ticket: %d\n", name, pthread_self(), ticket--);
            pthread_mutex_unlock(&mutex);
        }
        else
        {
            pthread_mutex_unlock(&mutex);
            break;
        }
    }
    return nullptr;
}

int main()
{
    pthread_mutex_init(&mutex, nullptr);
    pthread_t tid1, tid2, tid3, tid4;
    pthread_create(&tid1, nullptr, GetTicket, (void*)"thread-1");
    pthread_create(&tid2, nullptr, GetTicket, (void*)"thread-2");
    pthread_create(&tid3, nullptr, GetTicket, (void*)"thread-3");
    pthread_create(&tid4, nullptr, GetTicket, (void*)"thread-4");

    pthread_join(tid1, nullptr);
    pthread_join(tid2, nullptr);
    pthread_join(tid3, nullptr);
    pthread_join(tid4, nullptr);
    pthread_mutex_destroy(&mutex);
    return 0;
}
